package com.snake.mylibrary.mina;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.HandlerThread;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.snake.mylibrary.utils.LogUtil;

/**
 * mina框架测试，疑问？怎么查看是否是长连接状态？
 * libs中要有4个包，mina-core ,slf4j
 */

public class MinaService extends Service{
    private ConnectionThread mConnectionThread;
    @Override
    public void onCreate() {
        super.onCreate();
        mConnectionThread = new ConnectionThread("mina",getApplicationContext());
        mConnectionThread.start();
        LogUtil.e("MinaService开启");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.e("onStartCommand");
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mConnectionThread.disConnection();
        mConnectionThread = null;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    /**
     *
     */
    class ConnectionThread extends HandlerThread{
        Context mContext;
        boolean isConnection;
        ConnectionManager mConnectionManager;
        public ConnectionThread(String name,Context context) {
            super(name);
            mContext = context;
            ConnectionConfig config = new ConnectionConfig.Builder(mContext)
                    .setIp("192.168.1.102")
                    .setPort(9999)
                    .setReadBufferSize(10240)
                    .setConnectionTimeout(10000)
                    .build();
            mConnectionManager = new ConnectionManager(config);
            LogUtil.e("ConnectionThread");

        }

        @Override
        protected void onLooperPrepared() {
            super.onLooperPrepared();
            LogUtil.e("onLooperPrepared");
            for ( ;;){
                isConnection = mConnectionManager.connect();
                if(isConnection){
                    break;
                }
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void disConnection(){
            mConnectionManager.disConnection();
        }
    }
}
